<template>
  <div
      v-show="isShow"
      class="back-to-top"
      @click="scrollToTop"
  >
    <SvgIcon class="icon" icon-class="top" />
    <span>Top</span>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import SvgIcon from "@/components/common/SvgIcon.vue";

/**
 * 控制返回顶部按钮的显示逻辑与滚动行为
 * 使用Vue3 Composition API实现，包含滚动监听与平滑滚动功能
 */
// 响应式控制按钮显示状态的布尔值
const isShow = ref(false)

/**
 * 处理窗口滚动事件，根据滚动位置更新显示状态
 * 当垂直滚动超过200px时显示返回顶部按钮
 * 无参数和返回值
 */
const handleScroll = () => {
  isShow.value = window.pageYOffset > 200
}

/**
 * 执行平滑滚动到页面顶部的操作
 * 使用window.scrollTo实现，带平滑滚动效果
 * 无参数和返回值
 */
const scrollToTop = () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  })
}

// 组件挂载时注册滚动事件监听
onMounted(() => {
  window.addEventListener('scroll', handleScroll)
})

// 组件卸载时移除滚动事件监听（防止内存泄漏）
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})

</script>

<style scoped>
.back-to-top {
  position: fixed;
  right: 316px;
  bottom: 100px;
  width: 64px;
  height: 64px;
  line-height: 50px;
  text-align: center;
  background-color: #fff;
  color: #666666;
  border-radius: 8px;
  cursor: pointer;
  box-shadow: 4px 4px 32px rgba(0, 0, 0, 8%), 2px 2px 16px rgba(0, 0, 0, 4%);
  transition: all 0.3s;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .icon {
    width: 24px;
    height: 24px;
  }
  span {
    width: 26px;
    height: 22px;
    font-weight: 400;
    font-size: 14px;
    line-height: 20px;
  }
}

.back-to-top:hover {
  background-color: #EB5C88;
  color: #fff;
}

.back-to-top:active {
  transform: translateY(20px) scale(0.95);
}
</style>
